<template>
  <!-- 表单 -->
  <el-card style="margin: 10px 0px">
    <el-button
      v-if="hasPermission('sys:menu:add')"
      icon="Plus"
      type="primary"
      size="default"
      @click="addMenu"
      >添加菜单</el-button
    >
    <!-- table展示菜单信息 -->
    <el-table style="margin: 10px 0px" :data="menuArr" stripe rowKey="id">
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column
        label="名称"
        prop="name"
        treeKey="id"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="图标" prop="icon" show-overflow-tooltip>
        <template #default="scope">
          <el-icon>
            <component :is="scope.row.icon"></component>
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column label="类型" prop="type" show-overflow-tooltip>
        <template #default="scope">
          <el-tag v-if="scope.row.type === 0" size="small">目录</el-tag>
          <el-tag v-else-if="scope.row.type === 1" size="small" type="success"
            >菜单</el-tag
          >
          <el-tag v-else-if="scope.row.type === 2" size="small" type="info"
            >按钮</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        label="上级菜单"
        prop="parentName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="菜单URL"
        prop="url"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="授权标识"
        prop="perms"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="排序"
        prop="orderNum"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        width="150px"
        v-if="
          hasPermission('sys:menu:edit') || hasPermission('sys:menu:delete')
        "
      >
        <template #default="scope">
          <el-button
            type="primary"
            link
            size="small"
            icon="Edit"
            v-if="hasPermission('sys:menu:edit')"
            @click="updateMenu(scope.row)"
            >编辑</el-button
          >
          <el-popconfirm
            :title="`你确定要删除${scope.row.name}?`"
            width="260px"
            @confirm="deleteMenu(scope.row)"
          >
            <template #reference>
              <el-button
                link
                type="danger"
                size="small"
                icon="Delete"
                v-if="hasPermission('sys:menu:delete')"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <!-- 新增或者编辑 -->
  <drawer
    ref="drawerMenuRef"
    @cancel="handleCancelMenu"
    @submit="handleSubmitMenu"
  >
    <template v-slot:title>
      <h4>{{ menuParams.id ? "更新菜单" : "添加菜单" }}</h4>
    </template>
    <template v-slot:content>
      <el-form
        ref="formRef"
        :rules="rules"
        label-width="auto"
        :model="menuParams"
      >
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="menuParams.type">
            <el-radio
              v-for="(type, index) in menuTypeList"
              :label="index"
              :key="index"
              >{{ type }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :label="menuTypeList[menuParams.type] + '名称'"
          prop="name"
        >
          <el-input
            v-model="menuParams.name"
            :placeholder="menuTypeList[menuParams.type] + '名称'"
          ></el-input>
        </el-form-item>
        <el-form-item label="上级菜单" prop="parentName">
          <popup-tree-input
            :data="popupTreeData"
            :prop="
              menuParams.parentName == null || menuParams.parentName == ''
                ? '顶级菜单'
                : menuParams.parentName
            "
            :nodeKey="'' + menuParams.parentId"
            @handleCurrentChange="handleCurrentChanges"
          >
          </popup-tree-input>
        </el-form-item>
        <el-form-item
          v-if="menuParams.type !== 0 && menuParams.type !== 1"
          label="授权标识"
          prop="perms"
        >
          <el-input
            v-model="menuParams.perms"
            placeholder="如: sys:user:add, sys:user:edit, sys:user:delete"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="menuParams.type === 1" label="菜单路由" prop="url">
          <el-row>
            <el-col :span="22">
              <el-input
                v-model="menuParams.url"
                placeholder="菜单路由"
              ></el-input>
            </el-col>
            <el-col :span="2" class="icon-list__tips">
              <el-tooltip placement="top" effect="light" style="padding: 10px">
                <template #content>
                  <p>URL格式：</p>
                  <p>常规业务开发的功能URL，如用户管理，</p>
                  <p>Views目录下页面路径为 /asl/user, 此处填写 /asl/user。</p>
                </template>
                <el-icon style="margin-left: 10px">
                  <component is="Warning"></component>
                </el-icon>
              </el-tooltip>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item
          v-if="menuParams.type !== 2"
          label="排序编号"
          prop="orderNum"
        >
          <el-input-number
            v-model="menuParams.orderNum"
            controls-position="right"
            :min="0"
            label="排序编号"
          ></el-input-number>
        </el-form-item>
        <el-form-item v-if="menuParams.type !== 2" label="菜单图标" prop="icon">
          <el-input
            v-model="menuParams.icon"
            :readonly="false"
            placeholder="菜单图标名称（如：Warning）"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
  </drawer>
</template>
<script setup lang="ts">
import { onMounted, ref, reactive } from "vue";
import { reqFindMenuTree, reqMenuSave, reqMenuDelete } from "@/api/acl/menu";
import { validatorMenuName } from "@/utlis/validator";
import { ElMessage } from "element-plus";
import { hasPermission } from "@/utlis/permission";
// const label = ref("菜单名称");
const menuArr = ref([]);
const drawerMenuRef = ref();
const menuParams = reactive({
  id: 0,
  type: 1,
  name: "",
  parentId: 0,
  parentName: "",
  url: "",
  perms: "",
  orderNum: 0,
  icon: "",
  iconList: [],
});
const menuTypeList = ref(["目录", "菜单", "按钮"]);
const popupTreeData = ref([] as any);
const formRef = ref();
//关闭
const handleCancelMenu = () => {
  drawerMenuRef.value.close();
};
//保存
const handleSubmitMenu = async () => {
  //点击保存按钮的时候,务必需要保证表单全部复合条件在去发请求
  await formRef.value.validate();
  //按钮加载
  drawerMenuRef.value.showloading();
  let params: any = Object.assign({}, menuParams);
  const res = await reqMenuSave(params);
  if (res.code === 200) {
    //提示消息
    ElMessage({
      type: "success",
      message: menuParams.id !== 0 ? "编辑成功" : "添加成功",
    });
    handleCancelMenu();
    drawerMenuRef.value.hideloading();
    inintData();
  } else {
    //提示消息
    ElMessage({
      type: "error",
      message: res.msg,
    });
    handleCancelMenu();
    drawerMenuRef.value.hideloading();
  }
};
onMounted(() => {
  inintData();
});
const inintData = async () => {
  const res = await reqFindMenuTree();
  if (res.code === 200) {
    menuArr.value = res.data;
    popupTreeData.value = getParentMenuTree(res.data);
  }
};
// 获取上级菜单树
const getParentMenuTree = (tableTreeDdata: string[]) => {
  let parent = {
    parentId: 0,
    name: "顶级菜单",
    children: tableTreeDdata,
  };
  return [parent];
};
//搜索
// const handleSearch = () => {

// }
//重置
// const handleReset = () => {

// }
//添加菜单
const addMenu = () => {
  drawerMenuRef.value.open();
  //清空数据
  Object.assign(menuParams, {
    id: 0,
    type: 1,
    typeList: ["目录", "菜单", "按钮"],
    name: "",
    parentId: 0,
    parentName: "",
    url: "",
    perms: "",
    orderNum: 0,
    icon: "",
    iconList: [],
  });
};
//编辑
const updateMenu = (row: any) => {
  drawerMenuRef.value.open();
  Object.assign(menuParams, row);
};

//删除
const deleteMenu = async (row: any) => {
  const params = getDeleteIds([], row);
  const res = await reqMenuDelete(params);
  if (res.code === 200) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    inintData();
  } else {
    ElMessage({
      type: "error",
      message: res.msg,
    });
  }
};
// 获取删除的包含子菜单的id列表
const getDeleteIds = (ids: any, row: any) => {
  ids.push({ id: row.id });
  if (row.children != null) {
    for (let i = 0, len = row.children.length; i < len; i++) {
      getDeleteIds(ids, row.children[i]);
    }
  }
  return ids;
};
// 菜单树选中
const handleCurrentChanges = (data: any) => {
  menuParams.parentId = data.id;
  menuParams.parentName = data.name;
};

//表单校验的规则对象
const rules = {
  //菜单名称
  name: [{ required: true, trigger: "blur", validator: validatorMenuName }],
};
</script>
<style lang="scss" scoped></style>
